package com.lagou.filter;

import com.lagou.bean.User;
import com.lagou.service.UserService;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if(null == request.getSession().getAttribute("user")){
            //首先判断session中有没有user
            servletRequest.getRequestDispatcher("login.jsp").forward(servletRequest,servletResponse);
        }else{
            //取存在cookie中的用户名和密码
            String cookieUserName = "";
            String cookiePasswordWord = "";

            Cookie[] cookies = request.getCookies();
            for(Cookie cookie : cookies){
                if("username".equals(cookie.getName())){
                    cookieUserName = cookie.getValue();
                }
                if("password".equals(cookie.getName())){
                    cookiePasswordWord = cookie.getValue();
                }
            }
            UserService userService = new UserService();
            User user = userService.userLoginService(new User(cookieUserName, cookiePasswordWord));
            if (null == user) {
                servletRequest.getRequestDispatcher("login.jsp").forward(servletRequest,servletResponse);
            }else{
                filterChain.doFilter(request,response);
            }
        }

    }

    @Override
    public void destroy() {

    }
}
